#include "Mod5Algorithm.h"
#include <iostream>

void Mod5Algorithm::AddMorePoint()
{
	if (m_addStep == 0)
	{
		//add point
		for (int i=0;i<MAX_H;i++)
		for (int j=0;j<MAX_V;j++)
		{
			if ((i+j) % 5 == 2)
			{
				#if ENABLE_LOG	
				std::cout << "p:" << i <<":"<<j<<std::endl;
				#endif
				AddPoint(Point(i,j));
			}
		}
	}
	else if (m_addStep == 1)
	{
		for (int i=0;i<MAX_H;i++)
		for (int j=0;j<MAX_V;j++)
		{
			if ((i + j) % 5 == 4 &&  m_battle->IsUnkown(Point(i,j)))
			{
				#if ENABLE_LOG	
				std::cout << "p:" << i <<":"<<j<<std::endl;
				#endif
				AddPoint(Point(i,j));
			}
		}
	}
	else if (m_addStep == 2)
	{
		//old style
		for (int i=0;i<MAX_H;i++)
		for (int j=0;j<MAX_V;j++)
		{
			if ((i + j) % 5 == 0 &&  m_battle->IsUnkown(Point(i,j)))
			{
				#if ENABLE_LOG	
				std::cout << "p:" << i <<":"<<j<<std::endl;
				#endif
				AddPoint(Point(i,j));
			}
		}
		#if ENABLE_LOG	
		std::cout << "size:" << m_checkPoint.size() << std::endl;
		#endif

	}

	m_addStep++;
}

//init
void Mod5Algorithm::Initialize(BattleShipPtr battle)
{
	Mod3Algorithm::Initialize(battle);

	for (int i = 0; i < MAX_H; i++)
	for (int j = 0; j < MAX_V; j++)
	{
		m_random[i][j] = (float)rand() / RAND_MAX;
	}
	m_randomWeight = 0.4;
	m_nearestWeight = 0.4;
	m_posibilityWeight = 0.2;
}
//end

//guest a pos
Point Mod5Algorithm::GuessPos()
{
	CleanUp();
	RecheckPoint();

	if (m_checkPoint.size() == 0)
	{
		AddMorePoint();
	}

	Point result;
	float max_result = 0;

	PointArray::iterator ii;
	for (ii = m_checkPoint.begin(); ii != m_checkPoint.end(); ii++)
	{
		float value = m_randomWeight * m_random[ii->first][ii->second];
		float near =  m_battle->GetNearest(*ii) / 5;
		float count = GetTotalShip(*ii);
		//std::cout << ii->first<<":"<<ii->second <<" = " <<near<<":" << count << std::endl;
		if (near > 1) std::cout << "ERROR 1" << std::endl;
		if (count > 1) std::cout << "ERROR 2" << std::endl;
		value += m_nearestWeight * near + m_posibilityWeight * count;
		if (max_result < value)
		{
			 max_result = value;
			 result = *ii;
		}
	}

	//std::cout << "max_result = "<<max_result << std::endl;

	return result;
}//end

//calculate total possible ships
float Mod5Algorithm::GetTotalShip(Point p)
{
	int max = 34;
	int count = 0;
	for (int i = Ship::DESTROYER; i<=Ship::AIRCRAFT; i++)
	{
		if (!m_foundShip[i])
		{
			count += m_battle->GetTotalShip(p,Ship::GetLength((Ship::TypeOfShip)i));
			//max += Ship::GetLength((Ship::TypeOfShip)i) * 2;
		}
	}
	//std::cout << "Toal: " << count << std::endl;
	return 1.0f * count / max;
}//end